# -*- coding: utf-8 -*-

'''
Created on 28.07.2011

@author: Vlasov A. I. <root@proscript.ru>
'''
import re

from django import template
from django.contrib.auth.models import User

from okno.models import Statement
from settings import OKNO
from util import get_fio_initials

register = template.Library()

def __format_fio(data, case='n', gender='M', initials=False):
    '''
        Преобразует ФИО заявителя к нужному падежу
        Падежи:
            n : nominative - именительный
            g : genitive - родительный
            d : dative - дательный
            a : accusative - винительный
            ab: ablative - творительный
            p : prepositional - предложный
        Последний аргумент - сокращать ли инициалы.
    '''
    #tmp = __yandex_inflect(data, case, gender, initials)
    #if tmp:
    #return tmp
    
    cases = ['n', 'g', 'd', 'a', 'ab', 'p']
    
    fn = {
        'M' : {
            ur'[аеи])й$': {
                'g' : ur'\1я',
                'd' : ur'\1ю',
                'a' : ur'\1я',
                'ab': ur'\1ем',
                'p' : ur'\1ю',
            },
        },
        'F' : {
            ur')ка$': {
                'g' : ur'\1ки',
                'd' : ur'\1ке',
                'a' : ur'\1ку',
                'ab': ur'\1кой',
                'p' : ur'\1ке',
            },
            ur')а$': {
                'g' : ur'\1ы',
                'd' : ur'\1е',
                'a' : ur'\1у',
                'ab': ur'\1ой',
                'p' : ur'\1е',
            },
            ur')я$': {
                'g' : ur'\1и',
                'd' : ur'\1е',
                'a' : ur'\1ю',
                'ab': ur'\1ей',
                'p' : ur'\1е',
            },
            ur')ь$': {
                'g' : ur'\1и',
                'd' : ur'\1и',
                'a' : ur'\1ь',
                'ab': ur'\1ью',
                'p' : ur'\1и',
            },
        },
    }
    fn_x={
        'M' : {
            'g' : ur'\1а',
            'd' : ur'\1у',
            'a' : ur'\1ф',
            'ab': ur'\1ом',
            'p' : ur'\1е',
        },
    }
    
    p = {
        'M' : {
            ur'вич)$': {
                'g' : ur'\1а',
                'd' : ur'\1у',
                'a' : ur'\1а',
                'ab': ur'\1ем',
                'p' : ur'\1е',
            }
        },
        'F' : {
            ur'вн)а$': {
                'g' : ur'\1ы',
                'd' : ur'\1ой',
                'a' : ur'\1у',
                'ab': ur'\1ой',
                'p' : ur'\1е',
            }
        },
    }
    
    p_x = {}
    
    ln = {
        'M' : {
            ur'ев)$': {
                'g' : ur'\1а',
                'd' : ur'\1у',
                'a' : ur'\1а',
                'ab': ur'\1ым',
                'p' : ur'\1у',
            },
            ur')ий$': {
                'g' : ur'\1ого',
                'd' : ur'\1ому',
                'a' : ur'\1ого',
                'ab': ur'\1им',
                'p' : ur'\1ом',
            },
            ur')о$' : {
                'g' : ur'\1о',
                'd' : ur'\1о',
                'a' : ur'\1о',
                'ab': ur'\1о',
                'p' : ur'\1о',
            },
            ur')$' : {
                'g' : ur'\1а',
                'd' : ur'\1у',
                'a' : ur'\1а',
                'ab': ur'\1ым',
                'p' : ur'\1у',
            },    
        },
        'F' : {
            ur')а$': {
                'g' : ur'\1ой',
                'd' : ur'\1ой',
                'a' : ur'\1у',
                'ab': ur'\1ой',
                'p' : ur'\1ой',
            },
            ur')ая$': {
                'g' : ur'\1ой',
                'd' : ur'\1ой',
                'a' : ur'\1ую',
                'ab': ur'\1ой',
                'p' : ur'\1ой',
            },  
        }
    }
    
    ln_x = {
        'M' : {
            'g' : ur'\1а',
            'd' : ur'\1у',
            'a' : ur'\1а',
            'ab': ur'\1ым',
            'p' : ur'\1у',   
        },
    }
    
    if case not in cases or gender not in ['M', 'F']:
        return ''
    
    last_name = data['ln'].strip()
    if case != 'n':
        for _pattern, _cases in ln[gender].items():
            (last_name, num) = re.subn((ur'^([а-я]+'+_pattern), _cases[case], last_name, 1, re.U | re.I)
            if num:
                break
        if not num and gender in ln_x:
                last_name = re.sub((ur'^([а-я]+)$'), ln_x[gender][case], last_name, 1, re.U | re.I)
            
    if initials:
        try:
            patronymic = u'%s.' % data['p'][0].upper()
        except IndexError:
            patronymic = u''
        first_name = u'%s.' % data['fn'][0].upper()
        
    else:
        first_name = data['fn'].strip()
        patronymic = data['p'].strip()
        
        if case != 'n':
            for _pattern, _cases in fn[gender].items():
                (first_name, num) = re.subn((ur'^([а-я]+'+_pattern), _cases[case], first_name, 1, re.U | re.I)
                if num:
                    break
            if not num and gender in fn_x:
                first_name = re.sub((ur'^([а-я]+)$'), fn_x[gender][case], first_name, 1, re.U | re.I)
                
            for _pattern, _cases in p[gender].items():
                (patronymic, num) = re.subn((ur'^([а-я]+'+_pattern), _cases[case], patronymic, 1, re.U | re.I)
                if num:
                    break
            if not num and gender in p_x:
                patronymic = re.sub((ur'^([а-я]+)$'), p_x[gender][case], patronymic, 1, re.U | re.I)
                
    return u'%s %s %s'% (last_name, first_name, patronymic)
    
@register.filter()
def fio(obj, info='n|M'):
    info = info.split('|')
    
    case = info[0]
    try:
        gender = info[1]
    except IndexError:
        gender = 'M'
        
    try:
        initials = info[2]
    except IndexError:
        initials = False
    
    if isinstance(obj, Statement):
        tst = obj.inflect
        if tst:
            fio = {
                    'n': tst.nominative,
                    'g': tst.genitive,
                    'd': tst.dative,
                    'a': tst.accusative,
                    'ab': tst.ablative,
                    'p': tst.prepositional,  
                }.get(case, tst.nominative)
            if initials:
                fio = get_fio_initials(fio)
                
            return fio
        else:
            gender = obj.citizen.gender
            data = {
                'fn': obj.citizen.first_name,
                'p': obj.citizen.patronymic,
                'ln': obj.citizen.last_name,
            }
    elif isinstance(obj, User):
        profile = obj.get_profile()
        if OKNO['yandex_inflect'] and profile.genitive:
            fio = {
                'n': profile.nominative,
                'g': profile.genitive,
                'd': profile.dative,
                'a': profile.accusative,
                'ab': profile.ablative,
                'p': profile.prepositional,  
            }.get(case, profile.nominative)
            
            if initials:
                fio = get_fio_initials(fio)
                
            return fio
        else:
            (fn, p) = obj.first_name.split(' ')
            data = {
                'fn': fn,
                'p': p,
                'ln': obj.last_name,
            }
    else:
        return ''
        
    return __format_fio(data, case, gender, initials)

fio.is_safe = True